package com.kay;

import com.kay.annotation.dao.OrderAnnotationMapper;
import com.kay.annotation.dao.UserAnnotationMapper;
import com.kay.pojo.Order;
import com.kay.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Description: 基于注解方式开发测试
 * @Author: Kay
 * @CreateDate: 2021/6/27$ 22:09$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/6/27$ 22:09$
 */
public class AnnotationTest {
    private UserAnnotationMapper userAnnotationMapper;
    private OrderAnnotationMapper orderAnnotationMapper;


    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sessionFactory.openSession(true);
        userAnnotationMapper = sqlSession.getMapper(UserAnnotationMapper.class);
        orderAnnotationMapper = sqlSession.getMapper(OrderAnnotationMapper.class);
    }


    /**
     * 注解测试一对多
     */
    @Test
    public void testOneToMany(){
        List<User> userOrderList = userAnnotationMapper.findAllUserOrderList();
        if (userOrderList != null){
            for (User user : userOrderList) {
                System.out.println("user : " + user);
                List<Order> orderList = user.getOrderList();
                if (orderList != null){
                    System.out.println(" order list : ");
                    for (int i = 0; i < orderList.size(); i++) {
                        System.out.println(" order" + (i+1) + ": " + orderList.get(i) );
                    }
                }
                System.out.println("-----------------------------------------");
            }
        }
    }

    /**
     * 注解 多对多
     */
    @Test
    public void testOneToOne(){
        List<Order> orderList = orderAnnotationMapper.findAllOrderUser();
        if (orderList != null){
            for (Order order : orderList) {
                System.out.println(order);
                System.out.println("user : " + order.getUser());
                System.out.println("________________________________");
            }
        }
    }

    @Test
    public void testInsert(){
        User user = new User();
        user.setId(3);
        user.setUsername("Me");
        user.setPassword("11");
        user.setBirthday("2021-01-01");
        userAnnotationMapper.insertOne(user);
    }

    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(1);
        user.setUsername("Me");
        userAnnotationMapper.updateUsername(user);
    }

    @Test
    public void testDelete(){
        userAnnotationMapper.deleteById(3);
    }
}
